package com.andy.blog.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字段转换工具
 * Created by andy on 2023/4/21 11:11
 */
public class FieldCovertUtils {

    private static final Pattern LINE_PATTERN = Pattern.compile("_(\\w)");
    private static final Pattern HUMP_PATTERN = Pattern.compile("[A-Z]");

    /**
     * 下划线转驼峰
     *
     * @param str BATCH_ID
     * @return batchId
     */
    public static String lineToHump(String str) {
        if (StringUtils.isBlank(str)) {
            return str;
        }

        str = str.toLowerCase();
        Matcher matcher = LINE_PATTERN.matcher(str.toLowerCase());
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }

        matcher.appendTail(sb);
        return sb.toString();
    }


    /**
     * 驼峰转下划线
     *
     * @param str batchId
     * @return batch_id
     */
    public static String humpToLine(String str) {
        if (StringUtils.isBlank(str)) {
            return str;
        }
        // 首字母是大写，转小写
        if (Character.isUpperCase(str.charAt(0))) {
            str = StringUtils.uncapitalize(str);
        }

        Matcher matcher = HUMP_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }

        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * sql类型转Java类型
     * @param sqlType
     * @return
     */
    public static String sqlTypeToJavaType(String sqlType) {
        // 简单的SQL类型到Java类型的映射
        switch (sqlType.toUpperCase()) {
            case "VARCHAR":
            case "CHAR":
                return "String";
            case "BIGINT":
                return "Long";
            case "INT":
            case "INTEGER":
                return "Integer";
            case "DATETIME":
            case "TIMESTAMP":
                return "Date";
            default:
                return "Object"; // 处理未知类型
        }
    }
}
